import Vue from 'vue';
const app_info = require("@/static/appInfo.js");
const api_host = app_info.api_host
const appid = app_info.appid
const version = app_info.version
const api_prefix = api_host + '/addons/kzvote/'

//工具类
module.exports = {

	goto(url) {
		uni.navigateTo({
			url: url
		});
	},

	goreto(url) {
		uni.redirectTo({
			url: url
		});
	},

	gotore(url) {
		uni.reLaunch({
			url: url
		});
	},

	goback(delta = 1) {
		uni.navigateBack({
			delta: delta
		});
	},

	getData(key, is_clear = false) {
		var value = uni.getStorageSync(key);
		if (is_clear) {
			uni.setStorageSync(key, '');
		}
		return value;
	},

	setData(key, value) {
		uni.setStorageSync(key, value);
	},

	common(){
		this.http(this, 'common/config', '', 'get', false).then(res => {
			
			//#ifdef H5
			if(res.data.wechat_url1){
				if(document.URL.indexOf(res.data.wechat_url1) == -1){
					const url = document.URL.replace(res.data.wechat_url,res.data.wechat_url1);
					window.location.replace(url);
					return false;
				}
			}
			//#endif
			
			Vue.prototype.$store.commit('common/system', res.data.system);
			Vue.prototype.$store.commit('common/active', res.data.active);
			Vue.prototype.$store.commit('common/ad', res.data.ad);
			Vue.prototype.$store.commit('common/subscription', res.data.subscription);
			Vue.prototype.$store.commit('common/cdnurl', res.data.cdnurl);
			Vue.prototype.$store.commit('common/color', res.data.color);
			Vue.prototype.$store.commit('common/color_value', res.data.color_value);
			
			//#ifdef H5
			this.login();
			//#endif
			
			Vue.prototype.$isResolve()
		});
	},
	
	/**
	 * http请求
	 * @param handler
	 * @param path
	 * @param data
	 * @param method
	 * @param showLoading
	 * @returns {Promise<unknown>}
	 */
	http(handler, path, data = {}, method = 'post', showLoading = true) {
		if(!data){
			data = {}
		}
		const { platform } = uni.$u
		if(platform === 'h5') {
			data.platform = 'wechat';
		} else if(platform === 'weixin') {
			data.platform = 'wxapp';
		}
		if (method == 'get') {
			data.timestamp = Date.parse(new Date())
			// data['version'] = version
		}
	
		if (showLoading) {
			uni.showLoading({
				title: '加载中..',
				mask: true
			})
		}
	
		let header = {
			'content-type': 'application/json',
			'app-version': version
		};
		if (this.getData('token')) {
			header.token = this.getData('token')
		}
		
		return new Promise((resolve, reject) => {
			uni.request({
				url: api_prefix + path,
				method: method,
				data: data,
				header: header,
				success: (res => {
					if (res.statusCode == 200) {
						if (res.data.code == 1) {
							resolve(res.data)
						} else {
							if (path == 'person/vote') {
								resolve(res.data)
								return
							}
							uni.showModal({
								title: '提示',
								content: res.data.msg,
								showCancel: false
							})
						}
					} else {
						if (res.statusCode == 401) {
							this.login(true)
							resolve(res.data)
						} else {
							reject(res.data);
						}
						// reject(res)
					}
				}),
				fail: (res => {
					reject(res)
					// return false;
				}),
				complete: (res => {
					showLoading && uni.hideLoading()
				})
			})
		})
	},
	
	login(refresh = false) {
		// let user = {"id":21158,"username":"robin","nickname":"Robin","mobile":"","avatar":"/uploads/20230801/24d2967f645203876cf1a51003d31e14.jpeg","status":"normal","url":"/u/21158"}
		// let token = '91d1c2cd-6bc0-4066-893c-a9857de951f9'
		// uni.setStorageSync('user',user)
		// uni.setStorageSync('token',token)
		if (uni.getStorageSync('user')){
			return true;
		}
		function getQueryVariable(variable) {
			var query = window.location.search.substring(1);
			var vars = query.split("&");
			for (var i = 0; i < vars.length; i++) {
				var pair = vars[i].split("=");
				if (pair[0] == variable) {
					return pair[1];
				}
			}
			return (false);
		}
		var code = getQueryVariable('code')
		if (code && !refresh) {
			this.http(this, 'wechat/login', {
				code: code
			}, 'get', false).then(res => {
				uni.setStorageSync('user', res.data.user);
				uni.setStorageSync('token', res.data.token);
				if (uni.getStorageSync('original_url')){
					location.href = uni.getStorageSync('original_url');
					uni.setStorageSync('original_url', null);
				}
			});
		} else {
			const redirect_uri = encodeURIComponent(`${location.origin}`);
			//缓存授权前页面
			const url = document.URL 
			uni.setStorageSync('original_url', url);
			let autoUrl =
				`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo#wechat_redirect`;
			location.href = autoUrl;
		}
	},
	wxapp_login(){
		uni.login({
			success: res => {
				this.http(this, 'user/login', {
					code: res.code
				}, 'post', false).then(res => {
					uni.setStorageSync('user', res.data.user);
					uni.setStorageSync('token', res.data.token);
					// if (refresh) {
					// 	let url = uni.$u.pages()[0].$page.fullPath
					// 	if (url) {
					// 		this.goreto(url)
					// 	} else {
					// 		uni.reLaunch({
					// 			url: '/pages/index/index'
					// 		})
					// 	}
					// }
				});
			},
			fail(failRes) {
				uni.showModal({
					content: '登录失败，请重试'
				})
			}
		});
	},
	
	//公众号分享
	share(json){
		// #ifdef H5
		this.http(this, 'wechat/config', {url:encodeURIComponent(document.URL)}, 'post', false).then(res => {
			Vue.prototype.$jweixin.config({
				debug: res.data.debug,
				appId: res.data.appId,
				timestamp: res.data.timestamp,
				nonceStr: res.data.nonceStr,
				signature: res.data.signature,
				jsApiList: res.data.jsApiList,
				openTagList: ['wx-open-launch-weapp','wx-open-subscribe']
			})
			Vue.prototype.$jweixin.ready(function() {
				if (!json){
					let common = Vue.prototype.$store.state.common
					json = {
						title: common.system.share_title,
						imgUrl: common.cdnurl + common.system.share_img
					}
				}
				Vue.prototype.$jweixin.onMenuShareTimeline(json);
				Vue.prototype.$jweixin.onMenuShareAppMessage(json);
			})
		});
		//#endif
	},
	
	// 隐藏分享按钮
	hideShare(){
		// #ifdef H5
		this.http(this, 'wechat/config', {url:encodeURIComponent(document.URL)}, 'post', false).then(res => {
			Vue.prototype.$jweixin.config({
				debug: res.data.debug,
				appId: res.data.appId,
				timestamp: res.data.timestamp,
				nonceStr: res.data.nonceStr,
				signature: res.data.signature,
				jsApiList: res.data.jsApiList
			})
			Vue.prototype.$jweixin.ready(function() {
				Vue.prototype.$jweixin.hideOptionMenu();
			})
		});
		//#endif
		// #ifdef MP-WEIXIN
		uni.hideShareMenu()
		//#endif
	},
	
	link(link) {
		if (!link) {
			return true;
		}
		var open_type = link.open_type;
		var url = link.url;
		var params = link.params;
		if (open_type == 'wxapp') {
			uni.navigateToMiniProgram({
				appId: params.appid,
				path: params.path,
			});
		} else if (open_type == 'tel') {
			uni.makePhoneCall({
				phoneNumber: params.tel
			});
		} else if (open_type == 'web') {
			uni.setStorageSync('webview_url', params.url)
			uni.navigateTo({
				url: '/pages/webview/webview',
			});
		} else if (open_type == 'path') {
			uni.navigateTo({
				url: params.url,
			});
		} else {
			var param = '';
			if (params) {
				param = '?';
				for (var i in params) {
					param = param + i + '=' + params[i];
				}
			}
			uni.navigateTo({
				url: url + param
			});
		}
	},
	
	/**
	 * rich-text富文本中图片宽度最大100%
	 * @param {String} html
	 */
	formatRichText(html) {
		// 去掉img标签里的style、width、height属性
		let content_data = html.replace(/<img[^>]*>/gi, function(match, capture) {
			match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '')
			match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '')
			match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '')
			return match
		})

		// 修改所有style里的width属性为max-width:100%
		content_data = content_data.replace(/style="[^"]+"/gi, function(match, capture) {
			match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi,
				'max-width:100%;')
			return match
		})

		// 去掉<br/>标签
		content_data = content_data.replace(/<br[^>]*\/>/gi, '')
		// img标签添加style属性：max-width:100%;height:auto
		content_data = content_data.replace(/\<img/gi,
			'<img style="max-width:100%;height:auto;display:block;margin:0px auto;"')

		return content_data
	},

	/**
	 * 上传文件
	 * @returns {Promise<*>}
	 */
	uploadFile(handler, filePath, data = {}, fileType = 'image', showLoading = true) {

		if (showLoading) {
			uni.showLoading({
				title: '上传中..',
				mask: true
			})
		}

		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: api_host + '/api/common/upload',
				header: {
					'token': uni.getStorageSync('token'),
				},
				filePath: filePath,
				formData: data,
				name: 'file',
				success: (res) => {
					let data = JSON.parse(res.data)
					if (res.statusCode == 200) {
						if (data.code == 1) {
							resolve(data)
						} else {
							uni.showModal({
								title: '提示',
								content: data.msg,
								showCancel: false
							})
						}
					} else if (res.statusCode == 401) {
						// 未登录
						this.login(true)
					}
				},
				fail: (res) => {
					reject(res)
				},
				complete: (res => {
					showLoading && uni.hideLoading()
				})
			})
		})
	},
};
